package com.android.dumiaogou.activity.mine;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.dumiaogou.R;
import com.android.dumiaogou.model.data;
import com.android.dumiaogou.model.dataCallback;
import com.android.dumiaogou.model.member.query.QueryDataCallback;
import com.android.dumiaogou.model.member.query.QueryPojo;
import com.android.dumiaogou.model.member.query.QueryUnitPojo;
import com.android.dumiaogou.utils.ConstantsUrl;
import com.android.dumiaogou.utils.HttpUtils;
import com.android.dumiaogou.utils.ObjectUtils;
import com.android.dumiaogou.view.dialog.MainMsg;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class VerifyIdCardActivity extends TakePhotoActivity {

    @BindView(R.id.img_vertify_card1)
    ImageView imgCard1;
    @BindView(R.id.img_vertify_card2)
    ImageView imgCard2;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    @BindView(R.id.main_top_title)
    TextView mainTopTitle;
    @BindView(R.id.main_top_back)
    ImageView mainTopBack;
    @BindView(R.id.et_verify_name)
    EditText etName;
    @BindView(R.id.et_verify_id)
    EditText etID;

    @BindView(R.id.vertify_submit)
    TextView vertify_submit;


    private TakePhoto takePhoto;
    private VerifyIdCardActivity mcontext;
    private MainMsg mdialog;
    private int type = 1;
    private String card1Path;
    private String card2Path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_idcard);
        ButterKnife.bind(this);
        mcontext = VerifyIdCardActivity.this;
        ObjectUtils.StatusBarWhiteBg(mcontext, false);
        mainTopTitle.setText("实名认证");
        mainTopBack.setVisibility(View.VISIBLE);
        initUI();

        toQueryVerify();
    }

    /**
     * 编辑
     */
    private ArrayList<String> mList = new ArrayList<>();

    private void initUI() {
        //初始化
        takePhoto = getTakePhoto();

        mdialog = new MainMsg(mcontext);
        mdialog.setOnSetCameraClickListener(new MainMsg.OnTaktPhotoClickListener() {
            @Override
            public void onClickCamera() {
                Uri uri = configCompress();
                takePhoto.onPickFromCapture(uri);
                mdialog.close();
            }

            @Override
            public void onClickGallery() {
                configCompress();
                int size = mList.size();
                takePhoto.onPickMultiple(1 - size);
                mdialog.close();
            }
        });

    }

    //压缩
    private Uri configCompress() {
        File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.app_path) + System.currentTimeMillis() + ".png");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        CompressConfig config = new CompressConfig.Builder().setMaxSize(100 * 1024).setMaxPixel(1000).create();
        takePhoto.onEnableCompress(config, true);
        return imageUri;
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        ArrayList<TImage> images = result.getImages();
        mList.clear();
        mList.add(images.get(0).getCompressPath());
        upPic();
    }

    private void upPic() {
        if (mList.size() > 0) {
            boolean networkConnected = ObjectUtils.isNetworkConnected(mcontext);
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBER_UPLOAD;
            if (networkConnected) {
                progressLoading.setVisibility(View.VISIBLE);
                HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
                File file = new File(mList.get(0));
                HttpUtils.postfile(address, header, "upFile", file, upPicCallback);
            } else {
                ObjectUtils.toast(mcontext, "网络未连接");
            }
        }
    }

    dataCallback upPicCallback = new dataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            progressLoading.setVisibility(View.GONE);
            ObjectUtils.toast(mcontext, "上传失败");
        }

        @Override
        public void onResponse(data response, int id) {
            progressLoading.setVisibility(View.GONE);
            ObjectUtils.toast(mcontext, response.getMsg());
            if (response.getCode() == 0) {
                if (type == 1) {
                    card1Path = response.getData();
                    ObjectUtils.photo(mcontext, card1Path, imgCard1);
                } else {
                    card2Path = response.getData();
                    ObjectUtils.photo(mcontext, card2Path, imgCard2);
                }
            } else {
                if (response.getCode() == 40001) {
                    ObjectUtils.reLogin(mcontext);
                }
            }
        }
    };

    @OnClick({R.id.img_vertify_card1, R.id.img_vertify_card2, R.id.main_top_back, R.id.vertify_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_vertify_card1:
                type = 1;
                mdialog.show(mcontext.getWindow().getDecorView(), 1, null);
                break;
            case R.id.img_vertify_card2:
                type = 2;
                mdialog.show(mcontext.getWindow().getDecorView(), 1, null);
                break;
            case R.id.main_top_back:
                finish();
                break;
            case R.id.vertify_submit:
                if (card1Path == null || card2Path == null) {
                    ObjectUtils.toast(mcontext, "请上传身份证照片");
                    return;
                }
                toVerify();
                break;
        }
    }

    private void toVerify() {
        boolean networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBER_VERIFY;
        if (networkConnected) {
            progressLoading.setVisibility(View.VISIBLE);
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String, String> map = new HashMap<>();
            String realname = etName.getText().toString();
            String idcard = etID.getText().toString();
            map.put("realname", realname);
            map.put("idcard", idcard);
            map.put("card1", card1Path + "");
            map.put("card2", card2Path + "");

            HttpUtils.post(address, header, map, callback);
        } else {
            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }


    /**
     * 是否需要实名认证
     *
     */
    private void IsneedVerify() {
//        boolean networkConnected = ObjectUtils.isNetworkConnected(mcontext);
//        String address = ConstantsUrl.domain + ConstantsUrl.verifyidcard;
//        if (networkConnected) {
//            progressLoading.setVisibility(View.VISIBLE);
//            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
//            HashMap<String, String> map = new HashMap<>();
//            HttpUtils.get(address, header, map, dataqueryCallback);
//        } else {
//            ObjectUtils.toast(mcontext, "网络未连接");
//        }
    }
    /**
     * 去查询是否需要实名认证
     */
    private void toQueryVerify() {
        boolean networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.verifyidcard;
        if (networkConnected) {
            progressLoading.setVisibility(View.VISIBLE);
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String, String> map = new HashMap<>();
            HttpUtils.get(address, header, map, dataqueryCallback);
        } else {
            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }

    dataCallback callback = new dataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            progressLoading.setVisibility(View.GONE);
            ObjectUtils.toast(mcontext, "提交失败");
        }

        @Override
        public void onResponse(data response, int id) {
            progressLoading.setVisibility(View.GONE);
            ObjectUtils.toast(mcontext, response.getMsg());
            if (response.getCode() == 0) {
                finish();
            } else {
                if (response.getCode() == 40001) {
                    ObjectUtils.reLogin(mcontext);
                }
                return;
            }
        }
    };

    /**
     *
     */
    //查询实名认证的
    QueryDataCallback dataqueryCallback = new QueryDataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            progressLoading.setVisibility(View.GONE);
            ObjectUtils.toast(mcontext, "查询失败，稍后重试！");
            finish();
        }

        @Override
        public void onResponse(QueryPojo response, int id) {
            progressLoading.setVisibility(View.GONE);

            if (response.getCode() == 0) {

                if(response.getData()!=null&&response.getData().getId()!=null){

                    QueryUnitPojo pojo = response.getData();

//
//                    @BindView(R.id.img_vertify_card1)
//                    ImageView imgCard1;
//                    @BindView(R.id.img_vertify_card2)
//                    ImageView imgCard2;
//                    @BindView(R.id.progress_loading)
//                    FrameLayout progressLoading;
//                    @BindView(R.id.main_top_title)
//                    TextView mainTopTitle;
//                    @BindView(R.id.main_top_back)
//                    ImageView mainTopBack;
//                    @BindView(R.id.et_verify_name)
//                    EditText etName;
//                    @BindView(R.id.et_verify_id)
//                    EditText etID;

//                    EditText设置可以编辑和不可编辑状态
//                    设置不可编辑状态：
//                    editText.setFocusable(false);
//                    editText.setFocusableInTouchMode(false);
//
//                    设置可编辑状态：
//                    editText.setFocusableInTouchMode(true);
//                    editText.setFocusable(true);
//                    editText.requestFocus();


                    etName.setText(pojo.getRealname());
                    etID.setText(pojo.getCard());
                    ObjectUtils.photo(mcontext, pojo.getCard_image(), imgCard1);
                    ObjectUtils.photo(mcontext, pojo.getCard_image2(), imgCard2);
                    String state = pojo.getStatus();
                    if("0".equals(state)||"1".equals(state)){
                        ShowBystate();
                        vertify_submit.setText("审核中");

                    }else if("2".equals(state)){
                        ShowBystate();
                        vertify_submit.setText("已审核通过");

                    }else if("3".equals(state)){
                        ShowBystate();
                        vertify_submit.setText("未审核通过");

                    }else{

                    }
                    //#ef473a

                }

            } else {
                if (response.getCode() == 40001) {
                    ObjectUtils.reLogin(mcontext);
                }
                return;
            }
        }
    };

    private void ShowBystate(){
        vertify_submit.setEnabled(false);
        imgCard1.setEnabled(false);
        imgCard2.setEnabled(false);
        EdittextSet(etName);
        EdittextSet(etID);
        vertify_submit.setBackgroundResource(R.drawable.corner_red_bg_cannotclick);
    }

    private void EdittextSet(EditText edittext){
        edittext.setEnabled(false);
        edittext.setEnabled(false);
        edittext.setFocusable(false);
        edittext.setFocusableInTouchMode(false);
    }

}
